/*
 * mycp.c
 *
 *  Created on: 2021年3月15日
 *      Author: pc
 */

#include "apue.h"

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include<stdlib.h>
#include<string.h>

//这个没必要吧？
//extern int errno;
#define BUFFSIZE 4096

//目的路径，源路径
char *concat(char A[], char B[])
{
	char *p = A;
	char *q = B;
	q = strrchr(q,'/');
	while (*p)
	    p++;
	*p='/';
	p++;
	q=q==NULL?B:(q+1);
	while (*q)
		*p++ = *q++;
    *p='\0';
	return A;
}

char *deconcat(char A[], int len)
{
	char *p = A;
	while (len)
	{
	    p++;
	    len--;
	}
    *p='\0';
	return A;
}

int getlength(char C[])
{
	char *p = C;
	int len = 0;
	while (*p)
	{
	    p++;
	    len++;
	}
	return len;
}

int
main(int argc, char *argv[])
{
	if(argc != 3)
		err_quit("usage: mycp sourcefile_path destination(file)_path'");
	int srcfd = open(argv[1], O_RDONLY);
	if(errno != 0){
	    perror(argv[1]);
		close(srcfd);
		return 1;
	}
	int len;
	len=getlength(argv[2]);
	size_t desPathCap=strlen(argv[1])+len+1;
	char*desPath=malloc(desPathCap);
	memset(desPath,0,desPathCap);
	strcpy(desPath,argv[2]);
	int desfd = open(concat(desPath,argv[1]), O_CREAT | O_APPEND | O_RDWR | O_EXCL , S_IRWXU);
	if(errno == 20)//不是目录是文件路径
	{
		desfd = open(deconcat(desPath,len), O_CREAT | O_APPEND | O_RDWR | O_EXCL, S_IRWXU);
		if(errno == 17)
		{
			printf("file already exists, will you replace or add?[r/a]\n");
			char command = getchar();
			if(command == 'r')
			{
				desfd = open(desPath, O_TRUNC | O_RDWR  , S_IRWXU);
			}
			else if(command == 'a')
			{
				desfd = open(desPath, O_APPEND | O_RDWR  , S_IRWXU);
			}
		}
	}
	else if(errno == 17)//文件已存在
	{
		printf("file already exists, will you replace or add?[r/a]\n");
		char command = getchar();
		if(command == 'r')
		{
			desfd = open(desPath, O_TRUNC | O_RDWR , S_IRWXU);
		}
		else if(command == 'a')
		{
			desfd = open(desPath, O_APPEND | O_RDWR , S_IRWXU);
		}
	}
    char *buff[BUFFSIZE];
    ssize_t nbytes_out, nbytes_in;
    while((nbytes_out = read(srcfd, buff, BUFFSIZE)) > 0)
    {
    	nbytes_in = write(desfd, buff, nbytes_out);
    	if(nbytes_in != nbytes_out)
    		perror("write error");
    }
    if((nbytes_out < 0)&(errno != 0))
    	perror(argv[1]);
	close(srcfd);
	close(desfd);
	//printf("%s\n",desPath);
	free(desPath);
	return 0;
}
